//
//  ElevenFlowLayoutViewController.swift
//  swiftTS
//
//  Created by 航电 on 2020/4/14.
//  Copyright © 2020 航电. All rights reserved.
//

import UIKit

class ElevenCustomFlowLayout:UICollectionViewFlowLayout {
    override func prepare() {
        super.prepare();
        self.scrollDirection = .horizontal;
    }
    
    //改变每个cell的布局
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        let arr:[UICollectionViewLayoutAttributes] = super.layoutAttributesForElements(in: rect)!;
        //离屏幕中心越近 缩放比例越大
        let collectionOffSetX = self.collectionView?.contentOffset.x;
        let collectionCenterX = (self.collectionView?.frame.width)!/2;
        
        for index in 0..<arr.count {
            let layoutAttr:UICollectionViewLayoutAttributes = arr[index];
            //每个cell的中心点不变
            let scale = CGFloat(1-fabsf(Float(layoutAttr.center.x-collectionCenterX-collectionOffSetX!))/Float((self.collectionView?.frame.width)!));
//        print("itemCenter:\(layoutAttr.center.x),center:\(collectionCenterX),offset:\(collectionOffSetX),width:\(self.collectionView?.frame.width),scale:\(scale)")
            //itemCenter:332.5,center:207.0,offset:Optional(17.0),width:Optional(414.0),scale:0.7379226684570312
            //itemCenter:332.5,center:207.0,offset:Optional(118.0),width:Optional(414.0),scale:0.9818840622901917
            layoutAttr.transform = CGAffineTransform(scaleX: scale, y: scale);
        }
        
        return arr;
    }
    
    //是否允许所有cell改变尺寸，默认false 影响性能
    override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
        return true;
    }

    //自定义cell滑动到指定坐标
    override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
        var contentPoint = proposedContentOffset;
        var rect = CGRect.zero;
        rect.origin.x = contentPoint.x;
        rect.origin.y = 0;
        rect.size = (self.collectionView?.frame.size)!;
        
        let arr:[UICollectionViewLayoutAttributes] = super.layoutAttributesForElements(in: rect)!;
        
        let collectionCenterX = (self.collectionView?.frame.width)!/2;
        let collectionOffsetX = self.collectionView?.contentOffset.x;
        var minDistance = MAXFLOAT;
        for index in 0..<arr.count {
            let layoutAttr:UICollectionViewLayoutAttributes = arr[index];
            let distance = layoutAttr.center.x - collectionCenterX - collectionOffsetX!;
            if fabsf(Float(distance)) < fabsf(minDistance) {
                minDistance = Float(distance);
            }
        }
        
        contentPoint.x += CGFloat(minDistance);
        return contentPoint;
    }
//

}

class ElevenFlowLayoutViewController: UIViewController {

    fileprivate let cellId = "eleven_cell";
    fileprivate var _mainCollectionView:UICollectionView?;
    fileprivate var _mainFlowLayout:UICollectionViewFlowLayout?;
    fileprivate var _customFLowLayout = ElevenCustomFlowLayout();
    fileprivate lazy var mutDataArr:NSMutableArray = {
        var mutArr = NSMutableArray();
        mutArr.add(["img":"picture_01","title":"第一张"]);
        mutArr.add(["img":"picture_01","title":"第二张"]);
        mutArr.add(["img":"picture_01","title":"第三张"]);
        mutArr.add(["img":"picture_01","title":"第四张"]);
        mutArr.add(["img":"picture_01","title":"第五张"]);
        return mutArr;
    }();
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "FlowLayout";
        self.view.backgroundColor = .purple;
        // Do any additional setup after loading the view.
        self.onCreateUIForView();
    }

    //MARK:UI
    fileprivate func onCreateUIForView() {
        let titleArr = ["FlowLayout","CustomLayout"];
        let segmentCtl = UISegmentedControl(items: titleArr);
        segmentCtl.frame = CGRect(x: Tool.kScreenWith(width: 10), y: Tool.HEIGHT_STATUS_NAVBAR+20, width: screenMainSize.width-Tool.kScreenWith(width: 10)*2, height: 30)
        segmentCtl.setTitleTextAttributes([NSAttributedString.Key.font:UIFont.systemFont(ofSize: 16),NSAttributedString.Key.foregroundColor:UIColor.white], for: .normal);
        segmentCtl.setTitleTextAttributes([NSAttributedString.Key.font:UIFont.systemFont(ofSize: 16),NSAttributedString.Key.foregroundColor:UIColor.purple], for: .selected);
        segmentCtl.selectedSegmentIndex = 0;
        segmentCtl.isMomentary = false;
        segmentCtl.apportionsSegmentWidthsByContent = false;
        segmentCtl.tintColor = UIColor.red;
        segmentCtl.backgroundColor = .clear;
        segmentCtl.layer.borderColor = UIColor.white.cgColor;
        segmentCtl.layer.borderWidth = 1;
        segmentCtl.addTarget(self, action: #selector(onSelectSegmentAction(segment:)), for: .valueChanged);
        self.view.addSubview(segmentCtl);
        
        _mainFlowLayout = UICollectionViewFlowLayout();
        _mainFlowLayout?.scrollDirection = .horizontal;
        
        _mainCollectionView = UICollectionView(frame: CGRect(x: 0, y: segmentCtl.frame.maxY+10, width: screenMainSize.width, height: screenMainSize.height-segmentCtl.frame.maxY-10), collectionViewLayout: _mainFlowLayout!);
        _mainCollectionView?.backgroundColor = .clear;
        _mainCollectionView?.delegate = self;
        _mainCollectionView?.dataSource = self;
        _mainCollectionView?.register(EleventCell.self, forCellWithReuseIdentifier: cellId);
        self.view.addSubview(_mainCollectionView!);
    }
    
    //MARK:Actions
    @objc fileprivate func onSelectSegmentAction(segment:UISegmentedControl) {
        print("选中\(segment.selectedSegmentIndex)");
        if segment.selectedSegmentIndex == 0 {
            _mainCollectionView?.collectionViewLayout = _mainFlowLayout!;
        } else {
            _mainCollectionView?.collectionViewLayout = _customFLowLayout;
        }
    }

}

extension ElevenFlowLayoutViewController:UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return mutDataArr.count;
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell:EleventCell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! EleventCell;
      
        if self.mutDataArr.count > indexPath.row {
            cell.dataDic = (self.mutDataArr[indexPath.row] as! [String : AnyObject]);
        }
        
        return cell;
    }
}

extension ElevenFlowLayoutViewController:UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: screenMainSize.width/2, height: 460);
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        let topMarg = (collectionView.frame.height-460)/2;
        return UIEdgeInsets(top: topMarg, left: 0, bottom: topMarg, right: 0);
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return Tool.kScreenWith(width: 20);
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0;
    }
    
//    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
//
//    }
//
//    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
//
//    }
}
